package com.one.square.user.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.one.square.core.domain.LoginAppUser;
import com.one.square.core.entity.BaseEntity;
import com.one.square.core.entity.SysMenu;
import com.one.square.core.entity.SysRole;
import com.one.square.core.entity.SysUser;
import com.one.square.user.server.mapper.SysUserMapper;
import com.one.square.user.server.service.SysMenuService;
import com.one.square.user.server.service.SysRoleService;
import com.one.square.user.server.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author cwm
 * @Description
 * @date 2021/10/21 下午12:27
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public LoginAppUser findByUsername(String username) {
        SysUser sysUser = this.baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        return getLoginAppUser(sysUser);
    }

    @Override
    public LoginAppUser findByMobile(String mobile) {
        SysUser sysUser = this.baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getMobile, mobile));
        return getLoginAppUser(sysUser);
    }


    private LoginAppUser getLoginAppUser(SysUser sysUser) {
        if (sysUser != null) {
            LoginAppUser loginAppUser = new LoginAppUser();
            BeanUtils.copyProperties(sysUser, loginAppUser);

            List<SysRole> sysRoles = sysRoleService.findByUserId(sysUser.getId());
            // 设置角色
            loginAppUser.setRoles(sysRoles);

            if (!CollectionUtils.isEmpty(sysRoles)) {
                List<Long> roleIds = sysRoles.parallelStream().map(BaseEntity::getId).collect(Collectors.toList());
                List<SysMenu> menus = sysMenuService.findByRoleIds(roleIds);
                if (!CollectionUtils.isEmpty(menus)) {
                    Set<String> permissions = menus.parallelStream().map(p -> p.getPath())
                            .collect(Collectors.toSet());
                    // 设置权限集合
                    loginAppUser.setPermissions(permissions);
                }
            }
            return loginAppUser;
        }
        return null;
    }
}
